package com.sense.ioc.register;

import com.sense.ioc.annotation.Bean;
import com.sense.ioc.bean.BeanDefinition;

import java.util.Hashtable;

/**
 * User: LanJian
 * Date: 11-1-17
 * Time: 下午1:57
 */
public class IocRegister {
    protected static Hashtable<String, BeanDefinition> beanDefinitions = new Hashtable<String, BeanDefinition>();

    protected synchronized static void register(Class cls) {
        String clsName = cls.getName();
        if (!beanDefinitions.containsKey(clsName)) {
            beanDefinitions.put(clsName, validate(cls));
        } else {
            throw new RuntimeException(clsName + " duplicate");
        }
    }

    public static Object findBean(Class clazz) {
        Object object = null;
        BeanDefinition beanDefinition = beanDefinitions.get(clazz.getName());
        if (beanDefinition.isOK()) {
            try {
                object = beanDefinition.newInstance();
            } catch (Exception e) {
                throw new RuntimeException("new instance this class error!please check this class!", e);
            }
        }
        return object;
    }

    private static BeanDefinition validate(Class clazz) {
        if (clazz.isAnnotation() && clazz.isAnnotationPresent(Bean.class)) {
            Bean bean = (Bean) clazz.getAnnotation(Bean.class);
            BeanDefinition beanDefinition = new BeanDefinition(clazz.getName(), clazz, bean.singleton(), bean.initMethod());
            return beanDefinition;
        } else {
            throw new RuntimeException("this class is not register!");
        }
    }
}
